package com.demo.hotsearch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author : YU.TAN
 * @date : 2021/11/5 14:36
 */
@RestController
@RequestMapping("/search")
public class HotController {


    @Autowired
    @Qualifier("functionDomainRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

   private static final String HTO_SEARCH="HOT_SEARCH";

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public void search(@RequestParam("searchWord")String searchWord){
        //1、应当设计过期时间（热搜按天或者其他时间过期）
        Double score = redisTemplate.opsForZSet().incrementScore(HTO_SEARCH, searchWord, 1);
    }

    @RequestMapping(value = "/get/hotword",method = RequestMethod.GET)
    public List<String> getHotWord(@RequestParam("number") long number){
        List<String> list=new ArrayList<>();
//        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(HTO_SEARCH, 1, number);
//        assert typedTuples != null;
//        for (ZSetOperations.TypedTuple<Object> typedTuple : typedTuples) {
//            String value = (String) typedTuple.getValue();
//            list.add(value);
//        }

        Set<Object> objects = redisTemplate.opsForZSet().reverseRange(HTO_SEARCH, 0, number-1);
        for (Object value: objects) {
            list.add((String) value);
        }
        return list;
    }


}
